package com.weirong.smartvault.backservice.entity_model;

import com.weirong.smartvault.common.tools.constant.ConstantMethodNameTempMoneyLog;
import com.weirong.smartvault.dao.DictRepository;
import com.weirong.smartvault.dao.ForeignCurrencyTypeRepository;
import com.weirong.smartvault.entity.ForeignCurrencyType;
import com.weirong.smartvault.common.tools.spring.context.SpringContextUtil;
import com.weirong.smartvault.backservice.util.common.ReflectTool;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 于2017/12/6由 KFEB4 创建 .
 */
public class MoneyLogCollectionModel<T> {
    List<T> logs;
    DictRepository dictRepository;
    private ForeignCurrencyTypeRepository foreignCurrencyTypeRepository;

    public MoneyLogCollectionModel(List<T> logs){
        this.logs = logs;
        dictRepository = SpringContextUtil.getBean(DictRepository.class);
        foreignCurrencyTypeRepository = SpringContextUtil.getBean(ForeignCurrencyTypeRepository.class);

    }
    public List<T> getLogs(){
        return logs;
    }

    public String getCurrencyName() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (logs.size()==0){
            return "";
        }
        T log = logs.get(0);
        ForeignCurrencyType foreignCurrencyType = foreignCurrencyTypeRepository.getByCode((String) ReflectTool.runMethod(log,ConstantMethodNameTempMoneyLog.getCurrencyType));
        return foreignCurrencyType.getName();
    }
    public Integer getSize(){
        return logs.size();
    }
    public T first(){
        return logs.get(0);
    }
    public List<T> rest(){
        //剩余部分
        return logs.subList(1,logs.size());
    }
    public Integer getSum() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Integer sum = 0;
        for (T log:logs){
            sum+= (Integer) ReflectTool.runMethod(log,ConstantMethodNameTempMoneyLog.getSum);
        }
        return sum;
    }
    public static <G> Collection<MoneyLogCollectionModel<G>> makeCollection(List<G> list) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Map<String, MoneyLogCollectionModel<G>> logs = new HashMap<>();
        for (G log : list) {
            String currencyType = (String) ReflectTool.runMethod(log, ConstantMethodNameTempMoneyLog.getCurrencyType);
            MoneyLogCollectionModel<G> t;
            if (logs.containsKey(currencyType))
                t = logs.get(currencyType);
            else {
                t = new MoneyLogCollectionModel<G>(new ArrayList<>());
                logs.put(currencyType, t);
            }
            t.getLogs().add(log);
        }
        return logs.values();
    }
}
